import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:ddlmanager/backend/ddl.dart';
import 'package:ddlmanager/backend/app_state.dart';
import 'package:ddlmanager/utils/sort_drop_down.dart';

class DDLPage extends StatefulWidget {
  const DDLPage({super.key});

  @override
  State<DDLPage> createState() => _DDLPageState();
}

class _DDLPageState extends State<DDLPage> {
  late List<DDL> ddlList;
  late dynamic appState;
  late dynamic colorScheme;

  Future<void> showAddDDLDialog() async {
    String title = '';
    DateTime? inputDeadline;
    int selectedPriority = 1; // 默认高优先级

    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('添加 DDL'),
          content: StatefulBuilder(
            builder: (context, setState) {
              return SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题输入
                    TextField(
                      onChanged: (value) => title = value,
                      decoration: const InputDecoration(labelText: '标题'),
                    ),

                    // 日期选择
                    Center(
                      child: ElevatedButton(
                        onPressed: () async {
                          final DateTime? picked = await showDatePicker(
                            context: context,
                            initialDate: inputDeadline ?? DateTime.now(),
                            firstDate: DateTime(2000),
                            lastDate: DateTime(2100),
                          );
                          if (picked != null) {
                            setState(() => inputDeadline = picked);
                          }
                        },
                        child: Text(
                          inputDeadline == null
                              ? '选择截止日期'
                              : '截止日期: ${inputDeadline.toString().split(' ')[0]}',
                        ),
                      ),
                    ),

                    // 优先级选择（横向Chip排列）
                    const Padding(
                      padding: EdgeInsets.symmetric(vertical: 8),
                      child: Text('优先级:'),
                    ),
                    Wrap(
                      spacing: 8,
                      children:
                          [1, 2, 3].map((priority) {
                            final isSelected = priority == selectedPriority;
                            return ChoiceChip(
                              label: Text(
                                priority == 1
                                    ? '高'
                                    : priority == 2
                                    ? '中'
                                    : '低',
                                style: TextStyle(
                                  color:
                                      isSelected
                                          ? colorScheme.onPrimary
                                          : colorScheme.onSecondary,
                                ),
                              ),
                              selected: isSelected,
                              backgroundColor: colorScheme.secondary,
                              selectedColor: colorScheme.primary,
                              onSelected:
                                  (_) => setState(
                                    () => selectedPriority = priority,
                                  ),
                            );
                          }).toList(),
                    ),
                  ],
                ),
              );
            },
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                if (title.isNotEmpty && inputDeadline != null) {
                  appState.addDDL(
                    DDL(
                      title: title,
                      deadline: inputDeadline!,
                      priority: selectedPriority,
                      updateDate: DateTime.now(),
                      completionDate: DateTime.now(),
                      task: '',
                    ),
                  );
                  Navigator.pop(context);
                }
              },
              child: const Text('添加'),
            ),
          ],
        );
      },
    );
  }

  Future<void> showEditDDLDialog(int index) async {
    final originalDDL = ddlList[index];
    String title = originalDDL.title;
    DateTime deadline = originalDDL.deadline;
    int selectedPriority = originalDDL.priority; // 初始化为原DDL的优先级

    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('编辑 DDL'),
          content: StatefulBuilder(
            builder: (context, setState) {
              return SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题输入
                    TextField(
                      onChanged: (value) => title = value,
                      decoration: const InputDecoration(labelText: '标题'),
                      controller: TextEditingController(text: title),
                    ),

                    // 日期选择
                    Center(
                      child: ElevatedButton(
                        onPressed: () async {
                          final DateTime? picked = await showDatePicker(
                            context: context,
                            initialDate: deadline,
                            firstDate: DateTime(2000),
                            lastDate: DateTime(2100),
                          );
                          if (picked != null) {
                            setState(() => deadline = picked);
                          }
                        },
                        child: Text(
                          '截止日期: ${deadline.toString().split(' ')[0]}',
                        ),
                      ),
                    ),

                    // 优先级选择（横向Chip排列）
                    const Padding(
                      padding: EdgeInsets.symmetric(vertical: 8),
                      child: Text(
                        '优先级:',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ),
                    Wrap(
                      spacing: 8,
                      children:
                          [1, 2, 3].map((priority) {
                            final isSelected = priority == selectedPriority;
                            return ChoiceChip(
                              label: Text(
                                priority == 1
                                    ? '高'
                                    : priority == 2
                                    ? '中'
                                    : '低',
                                style: TextStyle(
                                  color:
                                      isSelected
                                          ? colorScheme.onPrimary
                                          : colorScheme.onSecondary,
                                ),
                              ),
                              selected: isSelected,
                              backgroundColor: colorScheme.secondary,
                              selectedColor: colorScheme.primary,
                              onSelected:
                                  (_) => setState(
                                    () => selectedPriority = priority,
                                  ),
                            );
                          }).toList(),
                    ),
                  ],
                ),
              );
            },
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                if (title.isNotEmpty) {
                  appState.updateDDL(
                    index,
                    DDL(
                      title: title,
                      deadline: deadline,
                      priority: selectedPriority, // 更新优先级
                      updateDate: DateTime.now(),
                      completionDate: originalDDL.completionDate,
                      task: originalDDL.task,
                    ),
                  );
                  Navigator.pop(context);
                }
              },
              child: const Text('保存'),
            ),
          ],
        );
      },
    );
  }

  // DDL详情对话框方法
  void showDDLDetailDialog(BuildContext context, DDL ddl) {
    final size = MediaQuery.of(context).size;
    final isMobile = size.width < 600;
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text(ddl.title),
            content: Container(
              width: isMobile ? size.width * 0.80 : 400, // 移动端占80%宽度
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 截止日期
                  ListTile(
                    leading: Icon(Icons.calendar_today),
                    title: Text('截止日期'),
                    subtitle: Text(ddl.deadline.toString().split(' ')[0]),
                  ),
                  ListTile(
                    leading: Icon(Icons.access_time),
                    title: Text('修改时间'),
                    subtitle: Text(ddl.updateDate.toString().split('.')[0]),
                  ),

                  // 优先级
                  ListTile(
                    leading: Icon(Icons.flag),
                    title: Text('优先级'),
                    subtitle: Text(
                      ddl.priority == 1
                          ? '高'
                          : ddl.priority == 2
                          ? '中'
                          : ddl.priority == 3
                          ? '低'
                          : '未知',
                    ),
                  ),
                  ListTile(
                    leading: Icon(Icons.star_outline_rounded),
                    title: Text('状态'),
                    subtitle: Text(ddl.isCompleted ? '已完成' : '未完成'),
                  ),
                ],
              ),
            ),
            contentPadding: EdgeInsets.symmetric(
              horizontal: isMobile ? 16 : 24, // 移动端更小的边距
              vertical: 20,
            ),
            actions: [
              TextButton(
                child: Text('确认'),
                onPressed: () => Navigator.pop(context),
              ),
            ],
          ),
    );
  }

  @override
  Widget build(BuildContext context) {
    appState = context.watch<AppState>();
    ddlList = appState.ddlList.ddlList;
    colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      appBar: AppBar(title: Text('这是你的DDL')),
      body: Stack(
        children: [
          Column(
            children: [
              ListTile(
                title: Text('排序: '),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 使用排序下拉菜单
                    SortDropdown(
                      initialSort: SortOption.title,
                      onSortChanged: (SortOption option) {
                        // 这里可以处理排序逻辑
                        switch (option) {
                          case SortOption.deadline:
                            appState.sortByDeadline(true);
                            break;
                          case SortOption.priority:
                            appState.sortByPriority(true);
                            break;
                          case SortOption.title:
                            appState.sortByTitle(true);
                            break;
                          case SortOption.updateTime:
                            appState.sortByUpdateTime(true);
                            break;
                        }
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                child: ListView.builder(
                  itemCount: ddlList.length,
                  itemBuilder: (context, index) {
                    final ddl = ddlList[index]; // 简化变量名

                    return ListTile(
                      title: Text(ddlList[index].title),
                      subtitle: Text(
                        '截止日期: ${ddlList[index].deadline.toString().split(' ')[0]}',
                      ),
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Tooltip(
                            message: '标记为已完成',
                            child: IconButton(
                              icon: Icon(Icons.check),
                              onPressed: () {
                                appState.completeDDL(index);
                              },
                            ),
                          ),
                          Tooltip(
                            message: '编辑',
                            child: IconButton(
                              icon: Icon(Icons.edit),
                              onPressed: () {
                                showEditDDLDialog(index);
                              },
                            ),
                          ),
                          Tooltip(
                            message: '删除',
                            child: IconButton(
                              icon: Icon(Icons.delete),
                              onPressed: () {
                                appState.deleteDDL(index);
                              },
                            ),
                          ),
                        ],
                      ),
                      onTap:
                          () => showDDLDetailDialog(context, ddl), // 直接传入DDL对象
                    );
                  },
                ),
              ),
            ],
          ),
          // 自定义位置的悬浮按钮
          Positioned(
            bottom: 20,
            right: 20,
            child: Tooltip(
              message: '添加',
              child: FloatingActionButton(
                onPressed: () {
                  showAddDDLDialog();
                },
                child: Icon(Icons.add),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
